package com.db.io;

import java.io.IOException;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class SelectorExample {
	
	public static void main(String[] args) throws IOException {
		ServerSocket srvSocket = new ServerSocket(9001);
		ServerSocketChannel srvChannel = srvSocket.getChannel();
		
		Selector selector = Selector.open();
		srvChannel.configureBlocking(false);
		srvChannel.register(selector, SelectionKey.OP_ACCEPT);

		ByteBuffer buf = ByteBuffer.allocate(48);
		while (true) {
			if (selector.select() > 0) {
				final Set<SelectionKey> keys = selector.selectedKeys();
				
				for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext();) {
					final SelectionKey key = it.next();
					
					if (key.isAcceptable()) {
						final SocketChannel channel = srvChannel.accept();
						channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
					} else if (key.isReadable()) {
						read((SocketChannel)key.channel(), buf);
					} else if (key.isWritable()) {
					
					}
					it.remove();
				}
			}
			break;
		}
		
		selector.keys().iterator().next().channel().close();
		srvChannel.close();
		srvSocket.close();
	}
	
	private static void read(SocketChannel channel, ByteBuffer buffer) throws IOException {
		int bytesRead = channel.read(buffer);
		
		if (bytesRead != -1) {
			buffer.flip();
			while(buffer.hasRemaining()) {
				System.out.println((char)buffer.get());
			}
			buffer.clear();
			bytesRead = channel.read(buffer);
		}
	}
}
